package com.jetpack_sunflower


import android.os.Bundle
import android.view.*
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.jetpack_sunflower.adapters.PlantAdapter
import com.jetpack_sunflower.databinding.FragmentPlantListBinding
import com.jetpack_sunflower.utils.InjectorUtils
import com.jetpack_sunflower.viewmodels.PlantListViewModel


/**
 * A simple [Fragment] subclass.
 *
 */
class PlantListFragment : Fragment() {

    private lateinit var plantListViewModel: PlantListViewModel
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        val binding = FragmentPlantListBinding.inflate(inflater, container, false)

        val mContext = context ?: return binding.root

        val viewModelFactory = InjectorUtils.providePlantListViewModelFactory(mContext)
        plantListViewModel = ViewModelProviders.of(this, viewModelFactory).get(PlantListViewModel::class.java)

        val plantAdapter = PlantAdapter()
        binding.plantList.adapter = plantAdapter
        subscribeUi(plantAdapter)
        setHasOptionsMenu(true)
        return binding.root
    }

    private fun subscribeUi(plantAdapter: PlantAdapter) {

        plantListViewModel.getPlants().observe(viewLifecycleOwner, Observer {
            if (it != null) {
                plantAdapter.submitList(it)
            }
        })
    }

    override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) {
        inflater?.inflate(R.menu.menu_plant_list, menu)
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        return when (item!!.itemId) {
            R.id.filter_zone -> {
                updateData()
                true
            }
            else -> {
                super.onOptionsItemSelected(item)
            }
        }
    }

    private fun updateData() {
        with(plantListViewModel) {
            if (isFilted()) {
                clearGrowZonNumber()
            } else {
                setGrowZoneNumber(9)
            }
        }
    }

}
